package mpcs.settings
{
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLLoaderDataFormat;
	import flash.net.URLRequest;

	public class Settings extends EventDispatcher
	{
		private  var loader:URLLoader;
		private  var xml:XML=null;
		
		public function Settings()
		{
			loader=new URLLoader();
			loader.dataFormat=URLLoaderDataFormat.TEXT;
		}
		
		public  function load(src:String):void
		{
			loader.addEventListener(Event.COMPLETE,loadComplete);
			loader.load(new URLRequest(src));
		}
		
		private  function loadComplete(e:Event):void
		{
			xml=new XML(loader.data);
			loader.removeEventListener(Event.COMPLETE,loadComplete);
			loader.addEventListener(IOErrorEvent.IO_ERROR,doIOError);
			loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR,doSecurityError);
			dispatchEvent(new SettingEvent(SettingEvent.COMPLETE));
		}
		
		private function doSecurityError(e:SecurityErrorEvent):void
		{
			dispose();
			var event:SettingErrorEvent=new SettingErrorEvent(SettingErrorEvent.ERROR);
			event.error=e.text;
			dispatchEvent(event);
		}
		
		private function doIOError(e:IOErrorEvent):void
		{
			dispose();
			var event:SettingErrorEvent=new SettingErrorEvent(SettingErrorEvent.ERROR);
			event.error=e.text;
			dispatchEvent(event);
		}
		
		public  function get key():String
		{
			return xml==null?"":xml.global.key[0].toString();
		}
		
		public  function get url():String
		{
			return xml==null?"":xml.global.url[0].toString();
		}
		
		public function get x():Number
		{
			return xml==null?0:Number(xml.info.x[0]);
		}
		
		public function get y():Number
		{
			return xml==null?0:Number(xml.info.y[0]);
		}
		
		public function get start():String
		{
			return xml==null?"":xml.road.start[0].toString();
		}
		
		public function get end():String
		{
			return xml==null?"":xml.road.end[0].toString();
		}
		
		private function dispose():void
		{
			loader.removeEventListener(Event.COMPLETE,loadComplete);
			loader.removeEventListener(IOErrorEvent.IO_ERROR,doIOError);
			loader.removeEventListener(SecurityErrorEvent.SECURITY_ERROR,doSecurityError);
		}
	}
}